//
// Created by tongj on 2024/1/13.
//

#ifndef _WRITEREADLOCK_CUH_
#define _WRITEREADLOCK_CUH_

template<typename T> void WriteReadLock<T>::READ_UNLOCK(WriteReadLock<T> *lk) {
  lk->unlock(READ_LOCK_TYPE);
}
template<typename T> void WriteReadLock<T>::READ_LOCK(WriteReadLock<T> *lk) {
  lk->lock(READ_LOCK_TYPE);
}
template<typename T> void WriteReadLock<T>::WRITE_UNLOCK(WriteReadLock<T> *lk) {
  lk->unlock(WRITE_LOCK_TYPE);
}

template<typename T> void WriteReadLock<T>::readLock() {
  _readers++;
  if (_readers == 1) {
	_lock.lock();
  }
}
template<typename T> void WriteReadLock<T>::readUnlock() {
  _readers--;
  if (_readers == 0) {
	_lock.unlock();
  }

}
template<typename T> void WriteReadLock<T>::writeLock() {
  _writers++;
  _lock.lock();
}
template<typename T> void WriteReadLock<T>::writeUnlock() {
  _writers--;
  _lock.unlock();
}

template<typename T> bool WriteReadLock<T>::lock(CONST int &sign) {
  switch (sign) {
  case READ_LOCK_TYPE:readLock();
	return true;
  case WRITE_LOCK_TYPE:writeLock();
	return true;
  default:return false;
  }
}
template<typename T> bool WriteReadLock<T>::unlock(CONST int &sign) {
  switch (sign) {
  case READ_LOCK_TYPE:readUnlock();
	return true;
  case WRITE_LOCK_TYPE:writeUnlock();
	return true;
  default:return false;
  }
}
template<typename T> bool WriteReadLock<T>::isLocked(CONST int &sign) CONST {
  return _lock.isLocked();
}
template<typename T> void WriteReadLock<T>::WRITE_LOCK(WriteReadLock<T> *lk) {
  lk->lock(WRITE_LOCK_TYPE);
}

#endif //_WRITEREADLOCK_CUH_
